package sign.tieba.utils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tieba.core.entity.TieBar;
import tieba.core.exception.SignException;
import tieba.core.utils.CommonsUtils;
import tieba.core.utils.TBUtils;
import cl.tools.http.method.BasicMethod;

import com.jayway.restassured.response.Cookie.Builder;

public class SignUtils {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(SignUtils.class);

	public static void signOne(String budss, String fn) {
		String url = "http://c.tieba.baidu.com/c/c/forum/sign";
		Map<String, Object> ps = new LinkedHashMap<String, Object>();
		ps.put("BDUSS", budss);
		ps.put("_client_type", 2);
		ps.put("kw", fn);
		ps.put("tbs", TBUtils.getTbs(new Builder("BDUSS", budss).build()));
		ps.put("sign", TBUtils.getSign(ps));
		String body = BasicMethod.post(url, ps).asString();
		Integer error_code = Integer.parseInt(CommonsUtils.regex(
				"\"error_code\":\"(\\w+)\"", body, 1));
		if (error_code == 0)
			return;
		String error_msg = CommonsUtils.regex("\"error_msg\":\"([^\"]+)\"",
				body, 1);
		throw new SignException(CommonsUtils.unicodeConvert(error_msg));
	}

	public static void signAll(final String budss, final List<TieBar> bs) {
		new Thread(new Runnable() {
			public void run() {
				for (TieBar bar : bs) {
					try {
						LOGGER.info("准备签到:" + bar.getFn() + "吧...");
						if (bar.isSign() != null && bar.isSign()) {// 如果已经签到过~
							LOGGER.info(bar.getFn() + "吧已经签到，自动跳过~");
							continue;
						}
						signOne(budss, bar.getFn());
						LOGGER.info(bar.getFn() + "吧签到完成..暂停5秒后执行下一个签到");
					} catch (SignException e) {
						LOGGER.error(bar.getFn()+"吧签到失败!");
					}
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
